<?php
set_include_path("../include;include");
require_once '/util/globals.php';
require_once '/dao/Database.php';
require_once '/model/Event.php';


/**
 * database access class for Event
 *
 * @author Thomas Crepain <contact@thomascrepain.be>
 */
class EventDAO
{
        const TABLENAME = 'event';

	/**
	 *
	 *
	 * @var Database
	 */
	private $db;

	/**
	 * Contains the event cache
	 *
	 * @var array
	 */
	private $eventCache = array();

	/**
	 * unique instance of this class
	 * Singleton pattern
	 *
	 * @var Database
	 */
	private static $uniqueInstance;


	/**
	 * constructs the DAO
	 */
	private function __construct()
	{
		// get database
                $this->db = Database::getInstance();
	}

	/**
	 * gets instance of database
	 *
	 * @return EventDAO
	 */
	public static function getInstance()
	{
		if(!isset(self::$uniqueInstance))
		{
			self::$uniqueInstance = new self();
		}

		return self::$uniqueInstance;
	}

        /**
	 * Returns the name
	 *
	 * @return integer
	 */
	public function getSubEventIdByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return is_null($this->eventCache[$EventId]['subevent_id']) ? (integer) -1 : (integer) $this->eventCache[$EventId]['subevent_id'];
	}

	/**
	 * Returns the name
	 *
	 * @return String
	 */
	public function getNameByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return $this->eventCache[$EventId]['name'];
	}

        /**
	 * Returns the description
	 *
	 * @return String
	 */
	public function getDescriptionByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return $this->eventCache[$EventId]['description'];
	}

        /**
	 * Returns the content
	 *
	 * @return String
	 */
	public function getContentByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return $this->eventCache[$EventId]['content'];
	}

        /**
	 * Returns the code
	 *
	 * @return String
	 */
	public function getCodeByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return $this->eventCache[$EventId]['code'];
	}

        /**
	 * Returns the prefix
	 *
	 * @return String
	 */
	public function getPrefixByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return $this->eventCache[$EventId]['prefix'];
	}

        /**
	 * Returns if an event is only for members
	 *
	 * @return boolean
	 */
	public function getOnlyMembersByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return (boolean) $this->eventCache[$EventId]['only_members'];
	}

        /**
	 * Returns if an event has auto complete functionality
	 *
	 * @return boolean
	 */
	public function getHasAutoCompleteByEventId(integer $EventId)
	{
		// build cache
		$this->buildCache($EventId);

		return (boolean) $this->eventCache[$EventId]['has_autocomplete'];
	}
	
	public function getDatetimeByEventId(integer $EventId) {
		// build cache
		$this->buildCache($EventId);

		return (integer) $this->eventCache[$EventId]['date_time'];
	}
	
	/**
         * Returns all events in the database
         *
         * @return array of Events
         */
	public function getAllEvents() {
		
		$records = (array) $this->db->getRecords("SELECT e.event_id, e.subevent_id, e.prefix, e.name, e.description, e.content, e.code, e.only_members, e.has_autocomplete, e.date_time
                                                                FROM ".self::TABLENAME." AS e
                                                                ORDER BY e.event_id ASC");
		$events = array();

                foreach ($records as $record) {
                    // fill event cache
                    $this->eventCache[$record['event_id']] = $record;
                }
		
		foreach ($records as $record) {
                    // make an object of every record
                    $event = Event::createNew($record['name'], $record['description'], $record['code'], (boolean) $record['only_members'], (boolean) $record['has_autocomplete'], $record['prefix']);
                    $event->setId((integer) $record['event_id']);
                    $event->setDatetime((integer) $record['date_time']);
                    $event->setSubEvent(Event::loadEvent((integer) $record['subevent_id']));
                    $events[] = $event;
		}
		
		return $events;
	}
	
	/**
	* Returns all events in the database
	*
	* @return array of Events
	*/
	public function getAllEventsOrderedByDate(boolean $asc) {
		$order = $asc ? "ASC" : "DESC";
		
		$records = (array) $this->db->getRecords("SELECT e.event_id, e.subevent_id, e.prefix, e.name, e.description, e.content, e.code, e.only_members, e.has_autocomplete, e.date_time
                                                                FROM ".self::TABLENAME." AS e
                                                                ORDER BY e.date_time ".$order);
		$events = array();

                foreach ($records as $record) {
                    // fill event cache
                    $this->eventCache[$record['event_id']] = $record;
                }
		
		foreach ($records as $record) {
                    // make an object of every record
                    $event = Event::createNew($record['name'], $record['description'], $record['code'], (boolean) $record['only_members'], (boolean) $record['has_autocomplete'], $record['prefix']);
                    $event->setId((integer) $record['event_id']);
                    $event->setDatetime((integer) $record['date_time']);
                    $event->setSubEvent(Event::loadEvent((integer) $record['subevent_id']));
                    $events[] = $event;
		}
		
		return $events;
	}


	/**
	 * Build the cache for the specified id
	 *
	 * @param integer	$eventId
	 */
	private function buildCache(integer $eventId)
	{
		// if cache is not build
		if(!isset($this->eventCache[$eventId]))
		{
                    // fill cache with this event
                    $this->eventCache[$eventId] = $this->db->getRecord("SELECT e.event_id, e.subevent_id, e.prefix, e.name, e.description, e.content, e.code, e.only_members, e.has_autocomplete, e.date_time
                                                                            FROM ".self::TABLENAME." AS e
                                                                            WHERE e.event_id = ?",
                                                                            array($eventId));
		}
	}


        /**
         * Saves the given event in the database
         *
         * @param Event $event
         * @return integer $id  id in database
         */
        public function save(Event $event){
            $id = 0;

            // is this a new event?
            if(is_null($event->getId())){
                $id = $this->db->insert(self::TABLENAME, array(
                        'subevent_id' => !is_null($event->getSubEvent()->getId()) ?  $event->getSubEvent()->getId() : NULL,
                        'name' => $event->getName(),
                        'prefix' => $event->getPrefix(),
                        'description' => $event->getDescription(),
                        'content' => $event->getContent(),
                        'code' => $event->getCode(),
                        'only_members' => $event->getOnlyMembers(),
                        'has_autocomplete' => $event->getHasAutocomplete(),
                		'date_time' => $event->getDatetime()));
            } else {
                $id = $event->getId();

                $this->db->update(self::TABLENAME, array(
                        'subevent_id' => !is_null($event->getSubEvent()->getId()) ?  $event->getSubEvent()->getId() : NULL,
                        'name' => $event->getName(),
                        'prefix' => $event->getPrefix(),
                        'description' => $event->getDescription(),
                        'content' => $event->getContent(),
                        'code' => $event->getCode(),
                        'only_members' => $event->getOnlyMembers(),
                        'has_autocomplete' => $event->getHasAutocomplete(),
                		'date_time' => $event->getDatetime()));
            }

            return $id;
        }
}

?>